import { ref } from 'vue'
// 使用华为云 OBS 的SDK
import ObsClient from 'esdk-obs-browserjs'

/**
 * 获取的的授权信息·50分钟内有效，可以每次上传都重新申请来防止过期
 * 可以传任何文件，尽量填写content-type内容（image/jpg等），如不知道，可以不填，但是需要传：
 * 文件表单名必须是 file
 * 上传后的文件名使用 key 开头加自定义名称
 * */
export const getObsToken = async (app) => {
  const url = new URL(`${app.requestParams.obs.obs_api_url}/cms`)
  url.searchParams.append('app_token', app.requestParams.obs.token) // 安全处理特殊字符
  try {
    const response = await fetch(url)
    if (!response.ok) {
      throw new Error(`OBS授权失败: ${response.status} ${response.statusText}`)
    }
    return response.json()
  } catch (error) {
    console.error('获取OBS令牌失败:', error)
    throw error
  }
}

export default function useObsUpload(app) {
  const uploadFileConfig = app.requestParams.obs.uploadFileConfig || {}
  const progress = ref(0) // 上传进度百分比
  const error = ref(null) // 错误信息
  const isUploading = ref(false) // 上传状态标识
  const uploadFile = async (file) => {
    progress.value = 0
    error.value = null
    isUploading.value = true
    const obsToken = await getObsToken(app)
    const timestamp = Date.now()
    const randomNum = Math.floor(Math.random() * 10) + 1
    const fileExtension = file.name.slice(file.name.lastIndexOf('.')).toLowerCase()
    const obsClient = new ObsClient({
      access_key_id: app.requestParams.obs.access_key_id,
      secret_access_key: app.requestParams.obs.secret_access_key,
      server: app.requestParams.obs.server,
    })
    const uniqueKey = `${obsToken.key /* 路径 */}${timestamp}${randomNum}${fileExtension}`
    let cp
    let hook
    return new Promise((resolve, reject) => {
      obsClient.uploadFile(
        {
          ...uploadFileConfig,
          Key: uniqueKey,
          SourceFile: file,
          ProgressCallback: function (transferredAmount, totalAmount) {
            progress.value = Math.floor((transferredAmount * 100.0) / totalAmount)
            if (hook && transferredAmount / totalAmount > 0.5) {
              // 暂停断点续传任务
              // hook.cancel();
            }
          },
          EventCallback: function (eventType, eventParam, eventResult) {
            // 处理事件响应
          },
          ResumeCallback: function (resumeHook, uploadCheckpoint) {
            // 获取取消断点续传上传任务控制参数
            hook = resumeHook
            // 记录断点
            cp = uploadCheckpoint
          },
        },
        function (err, result) {
          // 出现错误，再次调用断点续传接口，继续上传任务
          if (err) {
            obsClient.uploadFile(
              {
                ...uploadFileConfig,
                Key: uniqueKey,
                SourceFile: file,
                UploadCheckpoint: cp,
                ProgressCallback: function (transferredAmount, totalAmount) {
                  progress.value = Math.floor((transferredAmount * 100.0) / totalAmount)
                },
                EventCallback: function (eventType, eventParam, eventResult) {},
              },
              function (err) {
                error.value = err
                if (err) reject(err)
              },
            )
          } else {
            if (result.CommonMsg.Status === 200) return resolve(`${obsToken.domain}/${uniqueKey}`)
          }
        },
      )
    })
  }
  return { progress, error, isUploading, uploadFile }
}